package com.aerozhonghuan.logisticsmall.modules.user.logic;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.aerozhonghuan.logisticsmall.framework.base.MyAppliation;
import com.aerozhonghuan.logisticsmall.modules.common.ActivityDispatcher;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserBean;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserInfo;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.logisticsmall.utils.LocalCache;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * 描述 存储用户,以及登录等信息
 * @author zhangyonghui
 * 创建日期 2019-05-17
 */
public class UserInfoManager {
    private static final String TAG = UserInfoManager.class.getSimpleName();
    private static final String KEY_UUID = "KEY_UUID";
    private static final String KEY_DEVICE = "KEY_DEVICE";
    private static final String KEY_USER_INFO = "KEY_USER_INFO";
    private static final String KEY_USER_BEAN = "KEY_USER_BEAN";
    private static final Gson gson = new Gson();
    private static UserInfo userInfoCached;
    private static LocalCache localCache;

    private UserInfoManager() {
    }

    static {
        localCache = new LocalCache(MyAppliation.getApplication());
    }

    public static boolean isHaveDeviceId(){
        return !TextUtils.isEmpty(getDeviceId());
    }

    public static boolean isHaveUuid(){
        return !TextUtils.isEmpty(getUuid());
    }

    public static String getDeviceId() {
        String deviceId = null;
        if (localCache.hasKey(KEY_DEVICE)) {
            deviceId = localCache.getString(KEY_DEVICE);
        }
        return deviceId;
    }

    public static String getUuid() {
        String uuid = null;
        if (localCache.hasKey(KEY_UUID)) {
            uuid = localCache.getString(KEY_UUID);
        }
        return uuid;
    }

    public static void saveDeviceId(String deviceId){
        localCache.putString(KEY_DEVICE, deviceId);
    }

    public static void saveUuid(String uuid){
        localCache.putString(KEY_UUID, uuid);
    }

    /**
     * 退出登录 当前用户
     */
    public static void logout(final Context context) {
        LogUtil.d(TAG, "准备 退出登录");
        ProgressDialogIndicator progressDialogIndicator = new ProgressDialogIndicator(context);
        UserInfo currentUser = getCurrentUserBaseInfo();
        UserBean userBean = getCurrentUserDetailInfo();
        if (currentUser == null || userBean == null) {
            return;
        }
        // 清除通知栏通知，防止点击异常
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancelAll();
        //将注销状态通知给服务端
        UserInfoWebRequest.logout(MyAppliation.getApplication(), currentUser.getDevId(), currentUser.getUuid(), currentUser.getToken(), userBean.getCompany() == null ? "" : userBean.getCompany().getCode(), new CommonCallback<Object>() {
            @Override
            public void onSuccess(Object messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                LogUtil.d(TAG, "UserInfoWebRequest.logout 成功");
            }

            @Override
            public boolean onFailure(int httpCode, Exception exception, CommonMessage responseMessage, String allResponseString) {
                LogUtil.d(TAG, "UserInfoWebRequest.logout 失败");
                return super.onFailure(httpCode, exception, responseMessage, allResponseString);
            }
        });
        UserInfoManager.clearCurrentUser();
        userInfoCached = null;
        Intent intent = ActivityDispatcher.getIntent_LoginOnLogout(context);
        context.startActivity(intent);
    }

    /**
     * 保存用户授权基本信息
     * @param userInfo
     */
    public static void saveUserBaseInfo(UserInfo userInfo) {
        String json = gson.toJson(userInfo);
        localCache.putString(KEY_USER_INFO, json);
        userInfoCached = userInfo;
    }

    /**
     * 获取用户授权基本信息
     * @return
     */
    public static UserInfo getCurrentUserBaseInfo() {
        if (userInfoCached != null) {
            return userInfoCached;
        }
        String userInfoStr = localCache.getString(KEY_USER_INFO);
        if (TextUtils.isEmpty(userInfoStr)) {
            return null;
        }
        UserInfo userinfo = null;
        try {
            userinfo = gson.fromJson(userInfoStr, UserInfo.class);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return userinfo;
    }

    /**
     * 获得用户 详细信息
     *
     * @return
     */
    public static UserBean getCurrentUserDetailInfo() {
        String userBeanStr = localCache.getString(KEY_USER_BEAN);
        if (TextUtils.isEmpty(userBeanStr)) {
            return null;
        }
        UserBean userBean = null;
        try {
            userBean = gson.fromJson(userBeanStr, UserBean.class);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return userBean;
    }

    /**
     * 更新详细信息
     *
     * @param userbean
     */
    public static void saveUserDetailInfo(UserBean userbean) {
        String json = gson.toJson(userbean);
        localCache.putString(KEY_USER_BEAN, json);
    }


    /**
     * 清除 基本信息和详情信息
     */
    public static void clearCurrentUser() {
        LogUtil.d(TAG, "清除数据");
        localCache.remove(KEY_USER_INFO);
        localCache.remove(KEY_USER_BEAN);
    }
}
